#!/usr/bin/env python
# -*- coding: utf-8 -*-

import argparse
import os
import json
from modules.database.db_client import DBClient
import re


def parse_command_args():
    parser = argparse.ArgumentParser(description='SmartUI Web Server')
    parser.add_argument('--prefix', type=str, default='~/smartui', help='安装路径前缀')
    parser.add_argument('-c', '--config', type=str, default='config.json', help='配置文件路径')
    parser.add_argument("--enable-mock", action="store_true", help="使用mock模式运行")
    args = parser.parse_args()
    if not os.path.isabs(args.prefix):
        args.prefix = os.path.expanduser(args.prefix)
    if not os.path.isabs(args.config):
        args.config = os.path.join(args.prefix, args.config)
    return args

def init_app_config(app, args):
    # 加载配置文件
    with open(args.config, 'r') as config_file:
        config_data = json.load(config_file)

    # 检查配置文件中的所有配置项是否存在
    app_config_keys = [
        "HOST",
        "PORT",
        "DEBUG",
        "USE_RELOADER",
        "SECRET_KEY",
        "PROXY_SERVER",
        "DATABASE",
        "OPTIONS",
    ]
    for key in app_config_keys:
        if key not in config_data:
            app.logger.error(f"配置文件缺少必要的配置项: {key}")
            exit(1)
    proxy_server_config_keys = ["NAME", "HOST", "REQ_PORT", "SUB_PORT"]
    for proxy_server in config_data.get("PROXY_SERVER"):
        for key in proxy_server_config_keys:
            if key not in proxy_server:
                app.logger.error(f"配置文件缺少必要的配置项: {key}")
                exit(1)
    database_config_keys = ["NAME", "DB_URI"]
    for key in database_config_keys:
        if key not in config_data.get("DATABASE"):
            app.logger.error(f"配置文件缺少必要的配置项: {key}")
            exit(1)
    # 设置app.config
    app.config['WORKSPACE'] = args.prefix
    app.config.from_mapping(config_data)
    log_file = app.config.get("OPTIONS").get("LOG_FILE")
    if log_file is not None:
        if not os.path.isabs(log_file):
            log_file = os.path.join(app.config.get("WORKSPACE"), log_file)
        if not os.path.exists(os.path.dirname(log_file)):
            os.makedirs(os.path.dirname(log_file))
        app.logger.addHandler(logging.FileHandler(log_file))

# 解析数据库连接URI
def parse_db_uri(db_uri):
    """解析数据库连接URI"""
    # 检查是否为IP:port格式
    ip_port_pattern = r"^(\d{1,3}\.){3}\d{1,3}:\d+$"
    if re.match(ip_port_pattern, db_uri):
        ip, port = db_uri.split(":")
        return ip, int(port)

    # 检查是否为文件名格式
    filename_pattern = r"^[\w\.]+$"
    if re.match(filename_pattern, db_uri):
        return db_uri, None
        
    # 检查是否为绝对路径格式
    if os.path.isabs(db_uri):
        return db_uri, None

    # 不符合任何格式
    return None, None

def init_db_client(app):
    db_uri = app.config.get("DATABASE").get("DB_URI")
    match parse_db_uri(db_uri):
        case (None, None):
            app.logger.error(f"数据库连接URI格式错误: {db_uri}")
            exit(1)
        case (filepath, None):
            if not os.path.isabs(filepath):
                filepath = os.path.join(app.config.get('WORKSPACE'), 'database', filepath)
            if not os.path.exists(os.path.dirname(filepath)):
                os.makedirs(os.path.dirname(filepath))
                
            # 检查锁文件是否存在
            lock_file = filepath + '.lock'
            if os.path.exists(lock_file):
                try:
                    # 尝试删除锁文件
                    os.remove(lock_file)
                    app.logger.warning(f"检测到锁文件 {lock_file}，已自动删除")
                except Exception as e:
                    app.logger.error(f"无法删除锁文件 {lock_file}: {str(e)}")
                    exit(1)
                    
            db_client = DBClient(db_file=filepath)
        case (db_host, db_port):
            db_client = DBClient(host=db_host, port=db_host)
    return db_client    